

import { addCookie } from '@/utils/utils';
import { routerRedux } from 'dva/router';
import { stringify } from 'qs';
import {
  accountLogin,
  thirdLogin,
  ahydTempLogin,
  ahdxLogin,
  ahdxLoginByCode,
  getFakeCaptcha,
  getImageCaptcha,
  getIsNeedImageCode,
  getOauthType,
  infoList,
  downloadBwdaClient,
  getAeskey,
} from '@/services/api';
import { setAuthority } from '@/utils/authority';
import { notification } from 'antd';
import { getPageQuery } from '@/utils/utils';
import { saveAuthorization } from '@/utils/bwdautil';
import { reloadAuthorized } from '@/utils/Authorized';
import { queryUserDetail, removeToken } from '@/services/user';

export default {
  namespace: 'login',

  state: {
    status: undefined,
    loginType: 0, //内部，外部，
    outLoginUrl: '', //外部登录地址
  },

  effects: {
    *getAeskey({ payload }, { call }) {
      const response = yield call(getAeskey, payload);
      return response;
    },
    *login({ payload, callback }, { call, put }) {
      const response = yield call(accountLogin, payload);
      if (response.result == 'fail') {
        if (callback) callback(response);
        return;
      }

      if (response.result == 'ok') {
        let token = response.data.token;
        //保存所有返回
        saveAuthorization(token);
        let tempRole = [];
        response.data.roles.forEach(item => {
          tempRole.push(item.roleCode);
        });
        setAuthority(tempRole);
        reloadAuthorized();
        yield put(routerRedux.replace('/homepage'));
        // if (callback) callback(response);
      } else {
        notification.error({
          message: `登录失败`,
          description: response.msg,
        });
        return;
      }
    },
    *thirdLogin({ payload, callback }, { call, put }) {
      const response = yield call(thirdLogin, payload);
      if (response.result == 'fail') {
        if (callback) callback(response);
        return;
      }

      if (response.result == 'ok') {
        let token = response.data.token;
        //保存所有返回
        saveAuthorization(token);
        let tempRole = [];
        response.data.roles.forEach(item => {
          tempRole.push(item.roleCode);
        });
        setAuthority(tempRole);
        reloadAuthorized();
        yield put(routerRedux.replace('/homepage'));
        // if (callback) callback(response);
      } else {
        notification.error({
          message: `登录失败`,
          description: response.msg,
        });
        return;
      }
    },
    *ahydTempLogin({ payload, callback }, { call, put }) {
      const response = yield call(ahydTempLogin, payload);
      if (response.result == 'fail') {
        if (callback) callback(response);
        return;
      }

      if (response.result == 'ok') {
        addCookie('4AToken', payload.token, 0);

        let token = response.data.token;
        //保存所有返回
        saveAuthorization(token);
        let tempRole = [];
        response.data.roles.forEach(item => {
          tempRole.push(item.roleCode);
        });
        setAuthority(tempRole);
        reloadAuthorized();
        yield put(routerRedux.replace('/homepage'));
        // if (callback) callback(response);
      } else {
        notification.error({
          message: `登录失败`,
          description: response.msg,
        });
        return;
      }
    },
    *ahdxLogin({ payload }, { call, put }) {
      const response = yield call(ahdxLogin, payload);
      return response;
    },
    *ahdxLoginByCode({ payload, callback }, { call, put }) {
      const response = yield call(ahdxLoginByCode, payload);
      if (response.result == 'fail') {
        if (callback) callback(response);
        return;
      }

      if (response.result == 'ok') {
        let token = response.data.token;
        //保存所有返回
        saveAuthorization(token);
        let tempRole = [];
        response.data.roles.forEach(item => {
          tempRole.push(item.roleCode);
        });
        setAuthority(tempRole);
        reloadAuthorized();
        yield put(routerRedux.replace('/homepage'));
        // if (callback) callback(response);
      } else {
        notification.error({
          message: `登录失败`,
          description: response.msg,
        });
        return;
      }
    },
    *removeToken({ payload, callback }, { call, put }) {
      const response = yield call(removeToken, payload);
      if (callback) callback(response);
    },

    *queryUserDetail({ payload, callback }, { call, put }) {
      const response = yield call(queryUserDetail);
      if (response.result == 'fail') {
        notification.error({
          message: `查询用户信息失败`,
          description: response.msg,
        });
        return;
      }

      let data = response.data;
      if (data) {
        let roles = data.roles || [];
        let tempRole = [];
        roles.forEach(item => {
          tempRole.push(item.roleCode);
        });
        setAuthority(tempRole);
      }
      reloadAuthorized();
      yield put(routerRedux.replace('/homepage'));
    },

    *getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload);
    },
    *getImageCaptcha({ payload, callback }, { call }) {
      const response = yield call(getImageCaptcha, payload);
      if (callback) callback(response);
    },

    *getOauthType({ payload }, { call }) {
      const response = yield call(getOauthType, payload);

      yield put({
        type: 'saveOauthType',
        payload: response,
      });
    },

    *infoList({ payload, callback }, { call, put }) {
      const response = yield call(infoList, payload);

      yield put({
        type: 'saveinfoList',
        payload: response,
      });
      if (callback) callback(response);
    },

    *logout(_, { put }) {
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: false,
          currentAuthority: 'guest',
        },
      });
      reloadAuthorized();
      // redirect
      if (window.location.pathname !== '/login') {
        yield put(
          routerRedux.replace({
            pathname: '/login',
          })
        );
      }
    },
    *downloadBwdaClient({ payload, callback }, { call, put }) {
      const response = yield call(downloadBwdaClient, payload);
      if (callback) callback(response);
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      if (payload && payload.access_token && payload.roles && payload.roles.length > 0) {
        payload.status = 'ok';
        let roles = [];
        payload.roles.forEach(item => {
          roles.push(item.authority);
        });
        setAuthority(roles);
        //保存所有返回
        saveAuthorization(payload);
      }
      return {
        ...state,
        status: payload.status,
      };
    },
    saveLoginStatus(state, { payload }) {
      let token = payload.data;
      //保存所有返回
      saveAuthorization(token);
      return {
        ...state,
        status: payload.status,
      };
    },

    saveOauthType(state, { payload }) {
      return {
        ...state,
        loginType: payload.data,
      };
    },
  },
};
